<?php
/**
 * 登录人登录信息表
 */
use Think\Model;
class UserTokenModel extends Model {
    private $domain_map = array(
        '1' => 'web',
        '2' => 'iphone',
        '3' => 'android',
        '4' => 'ipad',
        '5' => 'android_pad',
    );

    /**
     * 添加用户登录信息
     * @return -1重复
     */
    public function addUserToken($user_id, $access_token, $refresh_token, $domain=0, $ip="") {
        $data = array();
        $data['user_id'] = strval($user_id);
        $data['access_token'] = strval($access_token);
        $data['refresh_token'] = strval($refresh_token);
        $data['domain'] = intval($domain);
        $data['ip'] = strval($ip);
        if ($this->where($data)->count() > 0) {
            return -1;
        }
        $data['ctime'] = time();
        return $this->add($data);
    }

    public function getUserIdByAccessToken($access_token) {
        $token_info = $this->where(array('access_token' => $access_token))->select();
        $token_info = $token_info[0];
        $now = time();
        if ($token_info['mtime'] > 0) {
            if ($now - ($token_info['mtime'] + C('ACCESS_TOKEN_EXPIRE')) > 0) {
                return 0;
            }
        } else if ($now - ($token_info['ctime'] + C('ACCESS_TOKEN_EXPIRE')) > 0) {
            return 0;
        }else if($token_info['status'] == 2) {
            return 0;
        }
        return $token_info['user_id'];
    }

    public function logoutUpdateStatus($access_token){
        if ($access_token != ''){
            $data = array('status' => 2, 'mtime' => time());
            $bool=$this->where(array('access_token' => $access_token))->save($data);
            return $bool;
        }
    }

    public function delUserStatus($user_id){
        if($$user_id != ''){
            return $this->where("id = {$user_id}")->setField('status',4);
        }
    }
}
